from __future__ import division
import numpy as np
import matplotlib.pyplot as plt
import math


#目标函数
def aimFunction(x):
    y = (x-50)**2
    return y
#绘制目标函数函数图像
def drawFunction():
    x = [i /10 for i in range(1000)]
    y = [0 for i in range(1000)]
    for i in range(1000):
        y[i] = aimFunction(x[i])
    plt.plot(x,y)
    plt.show()
#模拟退火
def SA():
    T0 = 100000 #初始化温度
    T = T0 
    Tmin = 10 #最低温度
    x = np.random.uniform(low = 0, high = 100)
    k = 50 # 迭代次数
    y = 0 #初始化结果
    t = 0 #时间
    while T >= Tmin:
        for i in range(k):
            #计算目标函数
            y = aimFunction(x)
            xNew = x + np.random.uniform(low = -0.055, high = 0.055)
            if (0 <= xNew  and xNew <= 100):
                yNew = aimFunction(xNew)
                if yNew < y:
                    x = xNew
                else:
                    p = np.exp( -(yNew - y)/T)
                    r = np.random.uniform(low = 0, high = 1)
                    if r < p:#一定概率接受
                        x = xNew
                    else:
                        pass
        t += 1
        T = T0/(1+t)
        print(x,aimFunction(x))
    return 

if __name__ == "__main__":
    SA()
    drawFunction()
